package net.neptech.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.neptech.context.SecurityContextHolder;
import net.neptech.domian.model.LoginUser;
import net.neptech.mapper.StaffMapper;
import net.neptech.model.sys.Staff;
import net.neptech.model.sys.User;
import net.neptech.repository.UserRepository;
import net.neptech.service.PermissionService;
import net.neptech.service.StaffService;
import net.neptech.service.UserService;
import net.neptech.utils.BeanCopyUtils;
import net.neptech.utils.SecurityUtils;
import net.neptech.vm.ResponseResult;
import net.neptech.vm.constant.SecurityConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * @Author: liyuxiang
 * @Date: 2025/8/14 10:18
 * @Description: TODO
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/user")
@Slf4j
public class UserController {
    @Autowired
    PermissionService permissionService;
    @Autowired
    UserRepository userRepository;
    @Autowired
    StaffService staffService;
    @Autowired
    UserService userService;

    /**
     * 注册用户
     */
    @PostMapping("register")
    public ResponseResult<User> register(@RequestBody User user) {
        userService.registerUser(user);
        return ResponseResult.success(user);
    }

    /**
     * 获取登录人信息
     *
     * @return
     */
    @GetMapping("getInfo")
    public ResponseResult<Object> getInfo() {
        LoginUser user = SecurityUtils.getLoginUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission();
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission();

        // 设置角色和权限到LoginUser对象
        user.setRoles(roles);
        user.setPermissions(permissions);
        String sessionKey = StpUtil.getStpLogic().getTokenSession().getId();
        log.info("SaSession Redis 键名: {}", sessionKey);
        Staff staff = staffService.getStaffInfoByUserId(user.getUserId());
        // 更新 SaSession 并强制同步到 Redis
        SaSession session = StpUtil.getTokenSession();
        session.set(SecurityConstants.LOGIN_USER, user);
        session.update();  // ⚠️ 关键：手动触发更新到持久层
        // 同时更新SecurityContextHolder中的LoginUser，确保SecurityUtils.getLoginUser()能获取到最新信息
        SecurityContextHolder.set(SecurityConstants.LOGIN_USER, user);

//        log.info("权限信息:{}", SecurityUtils.getLoginUser());

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("user", user);
        hashMap.put("staff", staff);
        hashMap.put("roles", roles);
        hashMap.put("permissions", permissions);

        return ResponseResult.success(hashMap);
    }

    @GetMapping("profile")
    public ResponseResult<Object> getProfile() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        User user = BeanCopyUtils.copyBean(loginUser, User.class);

        return ResponseResult.success(user);
    }

    @GetMapping("test")
    @SaCheckPermission("system:user:list")
    public ResponseResult<String> test() {
        return ResponseResult.success("test");
    }

    @PostMapping("selectUser")
    public ResponseResult<User> selectUser(@RequestBody User user) {
        user = userService.selectUser(user);
        return ResponseResult.success(user);
    }

    @GetMapping("selectByUserId")
    public ResponseResult<User> selectByUserId(@RequestParam("userId") Long userId) {
        User user = userRepository.findById(userId).orElse(null);
        return ResponseResult.success(user);
    }


}
